<template>
    <div class="historical-character-app">
        <h1 class="main-title">历史人物小百科</h1>
        <div class="search-section">
            <div class="search-container">
                <input v-model="searchQuery" type="text" placeholder="输入历史人物名称,朱元璋..." />
                <button @click="searchCharacter" class="search-button" :disabled="isLoading || !searchQuery.trim()">
                    <i class="search-icon">🔍</i>
                    <span v-if="isLoading" class="loading-spinner"></span>
                </button>
            </div>
            <p v-if="errorMessage" class="error-message">{{ errorMessage }}</p>
        </div>
        <div v-if="isLoading" class="loading-container">
            <div class="loading-spinner large"></div>
            <p>正在查询人物信息...</p>
        </div>
        <div v-else-if="currentCharacter" class="character-detail">
            <h2 class="character-name">{{ currentCharacter.name }}</h2>
            <!-- <img :src="currentCharacter.image" :alt="currentCharacter.name" /> -->
            <div class="info-section">
                <h3 class="section-title">人物简介</h3>
                <p>{{ currentCharacter.bio }}</p>
            </div>
            <div class="info-section">
                <h3 class="section-title">趣味故事</h3>
                <p>{{ currentCharacter.funStory }}</p>
            </div>
            <div class="info-section">
                <h3 class="section-title">关键事件</h3>
                <ul>
                    <li v-for="event in currentCharacter.keyEvents" :key="event">{{ event }}</li>
                </ul>
            </div>
            <div class="info-section">
                <h3 class="section-title">关联人物</h3>
                <ul>
                    <li v-for="related in currentCharacter.relatedCharacters" :key="related">
                        <a @click="loadRelatedCharacter(related)">{{ related }}</a>
                    </li>
                </ul>
            </div>
        </div>
        <div v-else class="no-result">
            <p>未找到相关历史人物，请尝试其他名称。</p>
        </div>
    </div>
</template>

<script>
import axios from 'axios';

export default {
    data() {
        return {
            searchQuery: '',
            currentCharacter: null,
            isLoading: false,
            errorMessage: '',
            // 模拟数据，实际使用时可从后端获取
            characters: {
                    name: '秦始皇',
                    image: 'https://example.com/qinshihuang.jpg',
                    bio: '秦始皇嬴政，首位完成华夏大一统的铁腕政治人物，建立首个多民族的中央集权国家。',
                    funStory: '秦始皇统一六国后，为了彰显自己的功绩，命人铸造了十二座巨大的铜人。据说这些铜人每座都重达千石，搬运和铸造都耗费了大量的人力和物力，成为当时一项极为浩大的工程。',
                    keyEvents: ['统一六国', '建立郡县制', '修筑长城'],
                    relatedCharacters: ['李斯', '赵高', '蒙恬']
                },
                // '汉武帝': {
                //     name: '汉武帝',
                //     image: 'https://example.com/hanwudi.jpg',
                //     bio: '汉武帝刘彻，西汉第七位皇帝，开创汉武盛世。',
                //     funStory: '汉武帝非常喜欢大宛国的汗血宝马，曾多次派使者前往求取。',
                //     keyEvents: ['独尊儒术', '开辟丝绸之路', '漠北之战'],
                //     relatedCharacters: ['卫青', '霍去病', '董仲舒']
                // }
            
        };
    },
    created() {
        // 初始化时加载第一个人物
        // this.currentCharacter = this.characters['秦始皇'];
    },
    methods: {
        async getCharacterArray() {
            if (!this.searchQuery.trim()) {
                this.errorMessage = '请输入人物姓名后再查询';
                return;
            }
            
            this.isLoading = true;
            this.errorMessage = '';
            
            // 利用axios 调用get_character_info接口，接口参数是character_name字符串
            await axios.get(`/get_character_info`, {
                params: {
                    character_name: this.searchQuery
                }
            })
            .then(response => {
                console.log('请求成功:', response.data);
                this.currentCharacter = response.data.data;
                
                // 检查结果是否包含"不知道"
                if (this.containsUnknownResponse(this.currentCharacter)) {
                    this.errorMessage = '抱歉，我们对这位人物的了解有限，请尝试其他人物';
                }
            })
            .catch(error => {
                if (error.response) {
                    // 请求已发出，但服务器响应状态码不在 2xx 范围内
                    console.log('服务器响应错误:', error.response.data);
                    console.log('状态码:', error.response.status);
                    console.log('响应头:', error.response.headers);
                    
                    // 处理400错误
                    if (error.response.status === 400) {
                        this.errorMessage = `无法找到"${this.searchQuery}"的相关信息，请检查名称是否正确`;
                        this.currentCharacter = null;
                    }
                } else if (error.request) {
                    // 请求已发出，但没有收到响应
                    console.log('没有收到服务器响应:', error.request);
                    this.errorMessage = '服务器未响应，请稍后再试';
                } else {
                    // 其他错误
                    console.log('错误信息:', error.message);
                    this.errorMessage = '查询过程中出现错误，请重试';
                }
                console.log('请求配置:', error.config);
            })
            .finally(() => {
                this.isLoading = false;
            });
        },
        searchCharacter() {
            if (!this.searchQuery.trim()) {
                this.errorMessage = '请输入人物姓名后再查询';
                return;
            }
            this.getCharacterArray();
        },
        loadRelatedCharacter(name) {
            this.searchQuery = name;
            this.searchCharacter();
        },
        containsUnknownResponse(character) {
            if (!character) return false;
            
            const checkString = (str) => {
                return str && typeof str === 'string' && str.toLowerCase().includes('不知道');
            };
            
            return checkString(character.bio) || 
                   checkString(character.funStory) || 
                   (character.keyEvents && character.keyEvents.some(checkString)) ||
                   (character.relatedCharacters && character.relatedCharacters.some(checkString));
        }
    }
};
</script>

<style scoped>
.historical-character-app {
    text-align: center;
    padding: 20px;
    max-width: 1200px;
    margin: 0 auto;
    box-sizing: border-box;
    /* 确保内边距和边框包含在宽度内 */
}

/* 标题样式优化 */
.main-title {
    background: linear-gradient(45deg, #3498db, #9b59b6);
    -webkit-background-clip: text;
    background-clip: text;
    color: transparent;
    text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.1);
    font-size: 2.5em;
    margin-bottom: 20px;
}

.character-name {
    background: linear-gradient(45deg, #42b983, #2c3e50);
    -webkit-background-clip: text;
    background-clip: text;
    color: transparent;
    text-shadow: 1px 1px 3px rgba(0, 0, 0, 0.1);
    font-size: 2em;
}

.section-title {
    background: linear-gradient(45deg, #e67e22, #d35400);
    -webkit-background-clip: text;
    background-clip: text;
    color: transparent;
    text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.1);
    font-size: 1.5em;
    margin-bottom: 15px;
}

.search-section {
    margin: 40px 0;
}

.search-container {
    display: flex;
    justify-content: center;
    align-items: center;
    max-width: 500px;
    margin: 0 auto;
}

.search-section input {
    padding: 15px 20px;
    width: 100%;
    /* 让输入框宽度自适应 */
    max-width: 400px;
    /* 限制最大宽度 */
    border: 2px solid #e0e0e0;
    border-radius: 30px 0 0 30px;
    font-size: 16px;
    transition: all 0.3s ease;
    box-sizing: border-box;
    /* 确保内边距和边框包含在宽度内 */
    margin-right: -2px;
}

.search-section input:focus {
    outline: none;
    border-color: #42b983;
    box-shadow: 0 0 8px rgba(66, 185, 131, 0.3);
}

.search-button {
    background: linear-gradient(45deg, #42b983, #3aa876);
    color: white;
    border: none;
    border-radius: 0 30px 30px 0;
    padding: 15px 25px;
    font-size: 16px;
    cursor: pointer;
    transition: all 0.3s ease;
    display: flex;
    align-items: center;
    justify-content: center;
    height: 50px;
    box-shadow: 0 2px 4px rgba(66, 185, 131, 0.3);
    position: relative;
    overflow: hidden;
}

.search-button:disabled {
    background: #cccccc;
    cursor: not-allowed;
    box-shadow: none;
}

.search-button::before {
    content: "";
    position: absolute;
    top: 0;
    left: -100%;
    width: 100%;
    height: 100%;
    background: rgba(255, 255, 255, 0.2);
    transition: all 0.3s ease;
}

.search-button:not(:disabled):hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(66, 185, 131, 0.5);
}

.search-button:not(:disabled):hover::before {
    left: 100%;
}

.search-icon {
    margin-right: 8px;
    font-style: normal;
    font-size: 1.2em;
    transition: transform 0.3s ease;
}

.search-button:not(:disabled):hover .search-icon {
    transform: rotate(360deg);
}

/* 加载动画 */
.loading-spinner {
    display: inline-block;
    width: 20px;
    height: 20px;
    border: 3px solid rgba(255, 255, 255, 0.3);
    border-radius: 50%;
    border-top-color: #fff;
    animation: spin 1s ease-in-out infinite;
    margin-left: 8px;
}

.loading-spinner.large {
    width: 50px;
    height: 50px;
    border-width: 4px;
}

.loading-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    margin: 40px 0;
}

@keyframes spin {
    to {
        transform: rotate(360deg);
    }
}

/* 错误消息 */
.error-message {
    color: #e74c3c;
    margin-top: 10px;
    font-size: 14px;
    animation: fadeIn 0.3s ease;
}

.character-detail {
    background: #fff;
    border: 1px solid #e0e0e0;
    padding: 30px;
    border-radius: 12px;
    margin: 40px auto;
    max-width: 800px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    transition: all 0.3s ease;
    box-sizing: border-box;
    /* 确保内边距和边框包含在宽度内 */
}

.character-detail:hover {
    transform: translateY(-5px);
    box-shadow: 0 8px 20px rgba(0, 0, 0, 0.15);
}

.character-detail img {
    max-width: 100%;
    /* 让图片宽度自适应 */
    border-radius: 8px;
    margin-bottom: 20px;
    animation: fadeIn 0.5s ease;
}

@keyframes fadeIn {
    from {
        opacity: 0;
        transform: scale(0.9);
    }

    to {
        opacity: 1;
        transform: scale(1);
    }
}

.info-section {
    margin-top: 25px;
    text-align: left;
    padding: 20px;
    background: #f8f9fa;
    border-radius: 8px;
}

.info-section p {
    line-height: 1.8;
    color: #495057;
}

.info-section ul {
    list-style: none;
    padding: 0;
}

.info-section li {
    padding: 10px 0;
    border-bottom: 1px solid #e0e0e0;
}

.info-section li:last-child {
    border-bottom: none;
}

.info-section a {
    color: #42b983;
    cursor: pointer;
    text-decoration: none;
    transition: color 0.3s ease;
}

.info-section a:hover {
    color: #2c3e50;
}

.no-result {
    color: #e74c3c;
    margin-top: 30px;
    font-size: 18px;
}

/* 媒体查询，针对小屏幕设备 */
@media (max-width: 768px) {
    .historical-character-app {
        padding: 5px;
    }

    .main-title {
        font-size: 2em;
    }

    .character-name {
        font-size: 1.8em;
    }

    .section-title {
        font-size: 1.3em;
    }

    .search-section input {
        font-size: 14px;
    }

    .search-button {
        padding: 15px 20px;
        font-size: 14px;
    }

    .character-detail {
        padding: 20px;
    }

    .info-section {
        padding: 15px;
    }
}
</style>